package protocol.telnet;

import io.netty.channel.*;

import java.util.Date;

@ChannelHandler.Sharable
public class TelnetServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.write("It is " +new Date() + "now.\n");
        ctx.flush();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        String response;

        boolean close = false;
        if (msg.isEmpty()){
            response = "拜托你写点什么东西\n";
        } else if ("bye".equals(msg.toLowerCase())){
            response = "拜拜！";
            close = true;
        }else {
            response = "这是你说的？ \""+msg+"\"";
            System.out.println("msg:"+msg);
        }

        ChannelFuture future = ctx.write(response);

        if (close){
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
